<template>
	<coreshop-page bgColor="rgba(0,0,0,0)" :isShowStatusBarHeight="false" :placeholder="false" showLoginModalDom
		needLoadingPage :loadingPage="loading">
		<view class="goods-detail">
			<!-- 商品详情 -->
			<GoodsDetail :goodsId="state.goodsDetailData?.id" :goodsDetailData="state.goodsDetailData"
				:swiperBanner="state.swiperBanner" :goodsDetailContent="state.goodsDetailContent"
				:userAgentGrade="state.userAgentGrade" :agentProductsList="state.agentProductsList"
				:goodsPromotionList="state.goodsPromotionList" :spesDesc="state.spesDesc" :shareType="ShareEnum.goods"
				@hanldeShowGoodSku="hanldeShowGoodSku">
			</GoodsDetail>

			<!-- 为您推荐 -->
			<GoodsDetailRecommend></GoodsDetailRecommend>

			<!-- 商品sku弹框 -->
			<GoodsDetailSkuPopup :showSku="state.showSku" :goodsDetailData="state.goodsDetailData"
				@handleAddCart="handleAddCart" @handleChangeGoodSku="handleChangeGoodSku" :safeAreaInsetBottom="false"
				@handleChangePopup="handleChangePopup" @handleBuyNow="handleBuyNow"></GoodsDetailSkuPopup>

			<!-- 底部导航按钮 -->
			<GoodsDetailBottomTabbar :price="state.skuPrice" @handleAddCart="hanldeShowGoodSku"
				@handleBuyNow="hanldeShowGoodSku"></GoodsDetailBottomTabbar>
		</view>
	</coreshop-page>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onShareAppMessage, onShareTimeline, onPullDownRefresh } from '@dcloudio/uni-app';
	import { queryGoodsDetail, queryCartNum, queryGoodsDetailByToken, queryPromotionList, queryAddCart } from '@/core/api';
	import type { Response, GoodsAgentListType, GoodsPromotionType, GoodsSkuListType } from "@/core/models";
	import { PromotionEnum, AddCartEnum, PaymentTypeEnum, ShareClientEnum, ShareModelEnum, ShareEnum } from '@/core/enum';
	import { UserToken, shareUrl } from '@/core/consts'
	import { useCartStore } from '@/core/store';
	import { handleRouteNavigateTo, handleShowToast, getShareUrl } from '@/core/utils';
	import GoodsDetail from '@/pages/components/goods-detail/index.vue';
	import GoodsDetailBottomTabbar from '@/pages/components/goods-detail/components/goods-detail-bottom-tabbar/goods-detail-bottom-tabbar.vue';
	import GoodsDetailSkuPopup from '@/pages/components/goods-detail/components/goods-detail-sku/goods-detail-sku.vue';
	import GoodsDetailRecommend from '@/pages/components/goods-detail/components/goods-detail-recommend/goods-detail-recommend.vue';
	import { useLoginStore } from '@/core/store';
	import { useLoadingFn } from '@/core/hooks';

	interface QueryParams {
		id : number;
	}

	/** 登录store */
	const _useLoginStore = useLoginStore();

	/** 购物车store */
	const _useCartStore = useCartStore();

	const state = reactive<{
		goodsDetailData : any;
		swiperBanner : Array<string>;
		goodsDetailContent : string;
		userAgentGrade : any;
		agentProductsList : Array<GoodsAgentListType>;
		goodsPromotionList : Array<GoodsPromotionType>;
		spesDesc : string;
		showSku : boolean;
		skuPrice : Number;
		shareUrl : string;
	}>({
		goodsDetailData: {},
		swiperBanner: [],
		goodsDetailContent: "",
		userAgentGrade: {},
		agentProductsList: [],
		goodsPromotionList: [],
		spesDesc: "",
		showSku: false,
		skuPrice: 0,
		shareUrl: "",
	});

	const loading = ref(true);
	let productId : number;

	const handleuGetGoodsDetail = useLoadingFn(getGoodsDetail, loading);
	onLoad((query : QueryParams) => {
		productId = Number(query.id);
		getGoodsDetailWithPromotionList();
	});

	onPullDownRefresh(async () => {
		await getGoodsDetailWithPromotionList();
		uni.stopPullDownRefresh();
	});


	async function getGoodsDetailWithPromotionList() {
		/** 获取商品详情 */
		handleuGetGoodsDetail(productId);
		/** 获取商品促销列表 */
		getPromotionList();
	}

	/** 获取商品详情 */
	async function getGoodsDetail(id : number) {
		let goodsDetail : any = null;
		if (uni.getStorageSync(UserToken)) {
			goodsDetail = await queryGoodsDetailByToken({
				id: id,
				data: true,
			})
		} else {
			goodsDetail = await queryGoodsDetail({
				id: id,
				data: true,
			})
		}

		state.goodsDetailData = goodsDetail.data;

		/** 默认规格 */
		state.spesDesc = goodsDetail?.data?.product?.spesDesc;
		/** 默认价格 */
		state.skuPrice = goodsDetail?.data?.price;

		/** 商品轮播图 */
		state.swiperBanner = goodsDetail?.data?.images?.split(',');
		/** 商品详情内容 */
		state.goodsDetailContent = goodsDetail?.data?.intro;
		/** 商品代理*/
		if (goodsDetail?.otherData) {
			/** 商品代理等级 */
			state.userAgentGrade = goodsDetail?.otherData?.userAgentGrade;
			/** 商品代理价格列表 */
			state.agentProductsList = goodsDetail?.otherData?.agentProducts?.map((item : GoodsAgentListType) => {
				goodsDetail?.data?.skuList?.sku_list?.forEach((itemChild : any) => {
					if (item.productId == itemChild._id) {
						item['name'] = itemChild.sku_name_arr[0];
					}
				})
				return item;
			});
		}
 
		/** 获取分享url */ 
		state.shareUrl = await getShareUrl({
			client: ShareClientEnum.wxMiNiProgram,
			url: shareUrl,
			type: ShareModelEnum.url,
			page: ShareEnum.goods,
			params: { goodsId: goodsDetail.data.id, } 
		}) 
		
		/** 如果用户登录，获取购物车数量 */
		if (uni.getStorageSync(UserToken)) {
			await getCartNum();
		}
	}

	/** 获取购物车数量 */
	const getCartNum = async () => {
		const num : Response<number> = await queryCartNum();
		_useCartStore.setCartNum(num?.data || 0);
	}

	/** 获取商品促销列表 */
	const getPromotionList = async () => {
		const promotionList : Response<Array<GoodsPromotionType>> = await queryPromotionList({
			id: PromotionEnum.promotion
		})
		state.goodsPromotionList = promotionList?.data;
	}

	/** 立即购买，打开sku弹框 */
	const hanldeShowGoodSku = () => {
		_useLoginStore.checkLogin(() => state.showSku = true);
	}

	/** sku弹框显示隐藏 */
	const handleChangePopup = (show : boolean) => {
		state.showSku = show;
	}

	/** sku选择 */
	const handleChangeGoodSku = (sku : GoodsSkuListType) => {
		state.spesDesc = sku.sku_name_arr.join(',');
		state.skuPrice = sku.price;
	}

	/** 添加购物车 */
	const handleAddCart = async ({ productId, nums } : any) => {
		const addCart : Response<number> = await queryAddCart({
			productId,
			nums,
			type: AddCartEnum.add,
		});
		if (addCart.status) {
			handleShowToast(addCart.msg, 'success');

			/** 添加成功后，重新获取购物车数量 */
			getCartNum();
			/** 关闭sku弹框 */
			state.showSku = false;
		} else {
			handleShowToast(addCart.msg);
		}
	}

	/** 立即购买 */
	const handleBuyNow = async ({ productId, nums } : any) => {
		const addCart : Response<number> = await queryAddCart({
			productId,
			nums,
			type: AddCartEnum.buy,
			cartType: PaymentTypeEnum.common,
		});
		if (addCart.status) {
			handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${addCart.data}`)
			/** 关闭sku弹框 */
			handleChangePopup(false);
		} else {
			handleShowToast(addCart.msg);
		}
	}

	/** 分享 */
	onShareAppMessage(() => {
		return {
			title: state.goodsDetailData.name,
			imageUrl: state.goodsDetailData.image,
			path: state.shareUrl
		}
	});
	onShareTimeline(() => {
		return {
			title: state.goodsDetailData.name,
			imageUrl: state.goodsDetailData.image,
			path: state.shareUrl
		}
	});
</script>

<style lang="scss" scoped>
	.goods-detail {
		padding-bottom: 175rpx;
	}
</style>